package com.atguigu.zk;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;

/**
 * Java代码连接zookeeper 进行小操作
 */
public class ZkDemo {

    private static String connectString = "192.168.200.128:2181,192.168.200.128:2182,192.168.200.128:2183";
    private static int sessionTimeout = 50*1000;
    private static String path = "/atguigu123";

    //Java代码连接zookeeper 进行小操作
    public static void main(String[] args) throws Exception {
        //1:连接 zookeeper服务
        ZooKeeper zooKeeper = startZK();
        //2:创建子节点 并添加数据
        String nodeValue = "java";
        String p = zooKeeper.create(path, nodeValue.getBytes(),
                ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        System.out.println(p);
        //3:查看子节点
        Stat stat = new Stat();
        byte[] data = zooKeeper.getData(p, new Watcher() {
            public void process(WatchedEvent watchedEvent) {

            }
        }, stat);
        System.out.println(stat);
        System.out.println(new String(data));
        //4:修改子节点
        //5:查看修改后的子节点
        if(zooKeeper != null)
             zooKeeper.close();
    }

    //连接 zookeeper服务
    private static ZooKeeper startZK() throws IOException {
        ZooKeeper zooKeeper = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
            public void process(WatchedEvent watchedEvent) {

            }
        });
        return zooKeeper;
    }
}
